<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.1" rel="stylesheet" type="text/css">


  <meta name="keywords" content="centos,">








  <link rel="shortcut icon" type="image/x-icon" href="/blog/favicon.ico?v=5.1.1">






<meta name="description" content="Shell简介：定义：shell即是一种命令语言，又是一种程序设计语言。  命令语言：他交互式地解释和执行用户输入的命令； 程序设计语言：他定义了各种变量和参数，并提供了血多在高级语言中才具有的控制结构，包括循环和分支。">
<meta name="keywords" content="centos">
<meta property="og:type" content="article">
<meta property="og:title" content="关于Shell">
<meta property="og:url" content="http://marsleo.gitee.io/blog/2017/07/21/关于Shell/index.html">
<meta property="og:site_name" content="NATURE">
<meta property="og:description" content="Shell简介：定义：shell即是一种命令语言，又是一种程序设计语言。  命令语言：他交互式地解释和执行用户输入的命令； 程序设计语言：他定义了各种变量和参数，并提供了血多在高级语言中才具有的控制结构，包括循环和分支。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-03-25T14:02:56.687Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="关于Shell">
<meta name="twitter:description" content="Shell简介：定义：shell即是一种命令语言，又是一种程序设计语言。  命令语言：他交互式地解释和执行用户输入的命令； 程序设计语言：他定义了各种变量和参数，并提供了血多在高级语言中才具有的控制结构，包括循环和分支。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>







  <title>关于Shell | NATURE</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">NATURE</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">MarsLeo Guo</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/blog/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="http://marsleo.gitee.io/blog/blog/2017/07/21/关于Shell/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="MarsLeo Guo">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/20170718142644.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="NATURE">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">关于Shell</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-07-21T15:23:52+08:00">
                2017-07-21
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/linux/" itemprop="url" rel="index">
                    <span itemprop="name">linux</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="Shell简介："><a href="#Shell简介：" class="headerlink" title="Shell简介："></a>Shell简介：</h4><h5 id="定义："><a href="#定义：" class="headerlink" title="定义："></a>定义：</h5><p>shell即是一种命令语言，又是一种程序设计语言。</p>
<ul>
<li>命令语言：他交互式地解释和执行用户输入的命令；</li>
<li>程序设计语言：他定义了各种变量和参数，并提供了血多在高级语言中才具有的控制结构，包括循环和分支。</li>
</ul>
<a id="more"></a>
<h5 id="两种执行命令的方式"><a href="#两种执行命令的方式" class="headerlink" title="两种执行命令的方式:"></a>两种执行命令的方式:</h5><ul>
<li><strong>交互式(<code>Interactive</code>):</strong> 用户输入一条命令，<code>shell</code>就解释一条。</li>
<li><strong>批处理（<code>Batch</code>）：</strong> 用户事先写一个<code>Shell</code>脚本，其中有很多命令，让shell一次把这些命令执行完，而不是一条一条的敲命令。</li>
</ul>
<hr>
<h4 id="几种常见的Shell"><a href="#几种常见的Shell" class="headerlink" title="几种常见的Shell"></a>几种常见的<code>Shell</code></h4><p>Unix、Linx上常见的Shell脚本解释器有bash、sh、csh、ksh等，习惯上把他们称作一种Shell。我们常说有几种Shell,其中说的是Shell脚本解释器。</p>
<h5 id="bash"><a href="#bash" class="headerlink" title="bash"></a>bash</h5><p>bash是Linux标准默认的shell</p>
<h5 id="第一个Shell脚本"><a href="#第一个Shell脚本" class="headerlink" title="第一个Shell脚本"></a>第一个<code>Shell</code>脚本</h5><p><strong>例1：</strong> 打开终端在root下建立一个shell脚本：</p>
<p>1.vim /root/test.sh</p>
<p>2.在test下输入：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">#!/bin/bash</span><br><span class="line">echo &quot;Hello World&quot;</span><br></pre></td></tr></table></figure></p>
<p>3.给脚本授权：<code>chmod + x /root/test.sh</code></p>
<p>4.执行脚本：./test.sh</p>
<blockquote>
<p><code>#!</code>是一个约定的标记，它告诉脚本需要什么Shell解释器来解决。</p>
</blockquote>
<p><strong>注意：</strong> 一定要写成<code>./test.sh</code>不要写成<code>test.sh</code>,如果写成后者运行时会到<code>Path</code>路径下去找。<br><strong>例2：</strong> 下面的脚本使用<strong>read</strong>命令从 <strong>stdin（标准输入）</strong> 获取输入并赋值给PERSON变量，最后在<strong>stdout（标准输出）</strong>输出：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">#!/bin/bash</span><br><span class="line">echo &quot;你的名字是：&quot;</span><br><span class="line">read PERSON</span><br><span class="line">echo &quot;Hello,$PERSON&quot;</span><br></pre></td></tr></table></figure></p>
<pre><code>结果：
你的名字：
郭仕帅
Hello,郭仕帅
</code></pre><hr>
<h4 id="变量："><a href="#变量：" class="headerlink" title="变量："></a>变量：</h4><h5 id="定义变量"><a href="#定义变量" class="headerlink" title="定义变量"></a>定义变量</h5><p>1.定义变量时，变量名不加 <strong>$</strong> 符，如：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">name=&quot;三德子&quot;</span><br><span class="line">age=12</span><br></pre></td></tr></table></figure></p>
<p>2.命名规则：数字、字母、下划线，开头必须是字母。</p>
<p>3.变量名与<strong>等号（=）</strong> 之间不能有空格。</p>
<h5 id="使用变量"><a href="#使用变量" class="headerlink" title="使用变量"></a>使用变量</h5><p>使用一个变量只要在变量前加<strong>美元符（$）</strong> 即可，如：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">name=&quot;三德子&quot;</span><br><span class="line">each $name</span><br><span class="line">each $&#123;name&#125;</span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>变量名外的花括号是可选的，加不加都行，加花括号是为了识别变量的边界，比如下面情况：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">for skill in java html shell php</span><br><span class="line">do</span><br><span class="line">    echo &quot;$&#123;skill&#125;说：我是世界上最好的语言！&quot;</span><br><span class="line">done</span><br></pre></td></tr></table></figure></p>
</blockquote>
<pre><code>结果：
java说：我是世界上最好的语言！
html说：我是世界上最好的语言！
shell说：我是世界上最好的语言！
php说：我是世界上最好的语言！
</code></pre><blockquote>
<p>建议所有变量加花括号</p>
</blockquote>
<h5 id="重新定义变量"><a href="#重新定义变量" class="headerlink" title="重新定义变量"></a>重新定义变量</h5><p>已定义的变量可以重新定义：后者覆盖前者。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">name=&quot;三德子&quot;</span><br><span class="line">echo $&#123;name&#125;</span><br><span class="line">name=&quot;法印&quot;</span><br><span class="line">echo $&#123;name&#125;</span><br></pre></td></tr></table></figure></p>
<pre><code>结果：
三德子
法印
</code></pre><h5 id="只读变量-readonly"><a href="#只读变量-readonly" class="headerlink" title="只读变量-readonly"></a>只读变量-<strong>readonly</strong></h5><p>使用<strong>readonly</strong>定义的变量时不可以修改的。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">readonly name=&quot;三德子&quot;</span><br><span class="line">echo $name</span><br><span class="line">或者</span><br><span class="line">name=&quot;三德子&quot;</span><br><span class="line">readonly name</span><br><span class="line">echo $name</span><br></pre></td></tr></table></figure></p>
<h5 id="删除变量-unset"><a href="#删除变量-unset" class="headerlink" title="删除变量-unset"></a>删除变量-<strong>unset</strong></h5><p>使用<strong>unset</strong>可以删除变量。除只读变量外。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">name=&quot;三德子&quot;</span><br><span class="line">unset name</span><br><span class="line">echo $name</span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>输出结果什么也没有。</p>
</blockquote>
<h5 id="变量类型"><a href="#变量类型" class="headerlink" title="变量类型"></a>变量类型</h5><p>运行shell时，会同时存在三种变量：<br>1) 局部变量</p>
<p>局部变量在脚本或命令中定义，仅在当前shell实例中有效，其他shell启动的程序不能访问局部变量。<br>2) 环境变量</p>
<p>所有的程序，包括shell启动的程序，都能访问环境变量，有些程序需要环境变量来保证其正常运行。必要的时候shell脚本也可以定义环境变量。<br>3) shell变量</p>
<p>shell变量是由shell程序设置的特殊变量。shell变量中有一部分是环境变量，有一部分是局部变量，这些变量保证了shell的正常运行</p>
<hr>
<h4 id="特殊变量"><a href="#特殊变量" class="headerlink" title="特殊变量"></a>特殊变量</h4><p>变量名只能包含数字、字母和下划线，因为某些包含其他字符的变量有特殊含义，这样的变量被称为特殊变量。<br>例如：查看当前shell的进程：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">echo $$</span><br></pre></td></tr></table></figure></p>
<table>
<thead>
<tr>
<th>变量</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td>$0</td>
<td>当前脚本的文件名</td>
</tr>
<tr>
<td>$n</td>
<td>传递给脚本或者函数的参数，第一个参数是$1</td>
</tr>
<tr>
<td>$#</td>
<td>传递给脚本或函数的参数个数。</td>
</tr>
<tr>
<td>$*</td>
<td>传递给脚本或函数的所有参数。</td>
</tr>
<tr>
<td>$@</td>
<td>传递给脚本或函数的所有参数。</td>
</tr>
<tr>
<td>$?</td>
<td>上一个命令退出的状态，或者函数的返回值。一般成功返回0，失败返回1</td>
</tr>
<tr>
<td>$$</td>
<td>查看当前shell的进程id</td>
</tr>
</tbody>
</table>
<h5 id="命令行参数"><a href="#命令行参数" class="headerlink" title="命令行参数"></a>命令行参数</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">echo &quot;文件的名称：$&#123;0&#125;&quot;</span><br><span class="line">echo &quot;第一个参数：$&#123;1&#125;&quot;</span><br><span class="line">echo &quot;所有参数：$&#123;@&#125;&quot;</span><br><span class="line">echo &quot;所有参数：$&#123;*&#125;&quot;</span><br><span class="line">echo &quot;参数的个数：$&#123;#&#125;&quot;</span><br></pre></td></tr></table></figure>
<p>运行：</p>
<pre><code>./test.sh 三德子  法印
</code></pre><p>结果：</p>
<pre><code>第一个参数：三德子
所有参数：三德子 法印
所有参数：三德子 法印
参数的个数：2
</code></pre><hr>
<h4 id="Shell-替换-Shell变量替换、Shell命令替换、转义字符"><a href="#Shell-替换-Shell变量替换、Shell命令替换、转义字符" class="headerlink" title="Shell 替换-Shell变量替换、Shell命令替换、转义字符"></a>Shell 替换-Shell变量替换、Shell命令替换、转义字符</h4><p>如果表达式中包含特殊字符，Shell将会进行替换。例如：在双引号中使用变量是一种替换，转义字符也是一种替换。<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#!/bin/bash</span><br><span class="line">a=10</span><br><span class="line">echo -e &quot;你猜他的年龄是多少岁？答案：$a \n&quot;</span><br></pre></td></tr></table></figure></p>
<p>结果：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">你猜他的年龄是多少岁？答案：10</span><br></pre></td></tr></table></figure></p>
<blockquote>
<p>如果没有<code>-e</code> <code>\n</code>就原样输出。<code>你猜他的年龄是多少岁？答案：10 \n</code></p>
</blockquote>
<p>下面的转移字符都可以用在<code>each</code>中：</p>
<table>
<thead>
<tr>
<th>转义字符</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td>\\</td>
<td>反斜杠</td>
</tr>
<tr>
<td>\a</td>
<td>警报，响铃</td>
</tr>
<tr>
<td>\b</td>
<td>退格(删除键)</td>
</tr>
<tr>
<td>\f</td>
<td>换页（FF）,将当前位置移动到下页开头</td>
</tr>
<tr>
<td>\n</td>
<td>换行</td>
</tr>
<tr>
<td>\r</td>
<td>回车</td>
</tr>
<tr>
<td>\t</td>
<td>水平制表符</td>
</tr>
<tr>
<td>\v</td>
<td>垂直制表符</td>
</tr>
</tbody>
</table>
<p>可以使用echo命令的-E选项禁止转义，默认也是不转义的。</p>
<h5 id="命令替换："><a href="#命令替换：" class="headerlink" title="命令替换："></a>命令替换：</h5><p>命令替换是指Shell可以先执行命令，将输出结果暂时保存。在适当的地方输出。<br>命令替换的语法：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">`command`</span><br></pre></td></tr></table></figure></p>
<p>下面的例子：将命令执行结果放在变量中</p>
<p>1.当前日期是：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">DATE=`date`</span><br><span class="line">echo &quot;日期是：$DATE&quot;</span><br></pre></td></tr></table></figure></p>
<p>结果：</p>
<pre><code>日期是2017年 04月 16日 星期日 23:15:34 PDT
</code></pre><p>2.系统当前登录的用户数是<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">USERS=`who | wc -l`</span><br><span class="line">echo &quot;系统当前的登录数为：$&#123;USERS&#125;&quot;</span><br></pre></td></tr></table></figure></p>
<p>结果：</p>
<pre><code>系统当前的登录数为：3
</code></pre><h5 id="变量替换"><a href="#变量替换" class="headerlink" title="变量替换"></a>变量替换</h5><p>变量替换可以根据变量的状态（是否为空、是否定义等）来改变他的值</p>
<table>
<thead>
<tr>
<th>形式</th>
<th>说明</th>
</tr>
</thead>
<tbody>
<tr>
<td>${var}</td>
<td>变量本来的值</td>
</tr>
<tr>
<td>${var:-word}</td>
<td>如果var为空或者被删除（unset），那么返回word，但不改变var的值</td>
</tr>
<tr>
<td>${var:=word}</td>
<td>如果var为空或者被删除（unset），那么返回word，同时改变var的值</td>
</tr>
<tr>
<td>${var:?message}</td>
<td>报错</td>
</tr>
<tr>
<td>${var:+word}</td>
<td>如果变量 var 被定义，那么返回 word，但不改变 var 的值。</td>
</tr>
</tbody>
</table>
<hr>
<h4 id="Shell运算符：Shell算数运算符、关系运算符、布尔运算符、字符串运算符、文件测试运算符"><a href="#Shell运算符：Shell算数运算符、关系运算符、布尔运算符、字符串运算符、文件测试运算符" class="headerlink" title="Shell运算符：Shell算数运算符、关系运算符、布尔运算符、字符串运算符、文件测试运算符"></a>Shell运算符：Shell算数运算符、关系运算符、布尔运算符、字符串运算符、文件测试运算符</h4><p>原生的bash不支持简答的数学运算，但可以通过其他命令来解释，最常用的是expr;</p>
<p>例如：计算两个数相加<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">#!/bin/bash</span><br><span class="line">val=`expr 2 + 2`</span><br><span class="line">echo $&#123;val&#125;</span><br></pre></td></tr></table></figure></p>
<p>结果：</p>
<pre><code>4
</code></pre><p>注意：</p>
<ul>
<li>表达式和运算符之间一定要有空格，例如：2+2是不对的必须写成2 + 2</li>
<li>表达式一定要被<code></code>包含，跟makedown一样。</li>
</ul>
<p>算数运算符：<br>注意：</p>
<ul>
<li>乘号：前边一定要加反斜杠（\*）</li>
<li>条件表达式：要放在方括号间，并且要有空格：[ $a == $b ] 比较相等。</li>
</ul>

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/centos/" rel="tag"># centos</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2017/07/21/centos相关/" rel="next" title="centos相关">
                <i class="fa fa-chevron-left"></i> centos相关
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2017/07/21/关于javaScript/" rel="prev" title="关于javaScript">
                关于javaScript <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image" src="/blog/20170718142644.jpg" alt="MarsLeo Guo">
          <p class="site-author-name" itemprop="name">MarsLeo Guo</p>
           
              <p class="site-description motion-element" itemprop="description">人法地，地法天，天法道，道法自然。</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/blog/archives">
                <span class="site-state-item-count">23</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/blog/categories/index.html">
                <span class="site-state-item-count">11</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/blog/tags/index.html">
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/1605220882/profile?topnav=1&wvr=6" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#Shell简介："><span class="nav-number">1.</span> <span class="nav-text">Shell简介：</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#定义："><span class="nav-number">1.1.</span> <span class="nav-text">定义：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#两种执行命令的方式"><span class="nav-number">1.2.</span> <span class="nav-text">两种执行命令的方式:</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#几种常见的Shell"><span class="nav-number">2.</span> <span class="nav-text">几种常见的Shell</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#bash"><span class="nav-number">2.1.</span> <span class="nav-text">bash</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#第一个Shell脚本"><span class="nav-number">2.2.</span> <span class="nav-text">第一个Shell脚本</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#变量："><span class="nav-number">3.</span> <span class="nav-text">变量：</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#定义变量"><span class="nav-number">3.1.</span> <span class="nav-text">定义变量</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#使用变量"><span class="nav-number">3.2.</span> <span class="nav-text">使用变量</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#重新定义变量"><span class="nav-number">3.3.</span> <span class="nav-text">重新定义变量</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#只读变量-readonly"><span class="nav-number">3.4.</span> <span class="nav-text">只读变量-readonly</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#删除变量-unset"><span class="nav-number">3.5.</span> <span class="nav-text">删除变量-unset</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#变量类型"><span class="nav-number">3.6.</span> <span class="nav-text">变量类型</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#特殊变量"><span class="nav-number">4.</span> <span class="nav-text">特殊变量</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#命令行参数"><span class="nav-number">4.1.</span> <span class="nav-text">命令行参数</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Shell-替换-Shell变量替换、Shell命令替换、转义字符"><span class="nav-number">5.</span> <span class="nav-text">Shell 替换-Shell变量替换、Shell命令替换、转义字符</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#命令替换："><span class="nav-number">5.1.</span> <span class="nav-text">命令替换：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#变量替换"><span class="nav-number">5.2.</span> <span class="nav-text">变量替换</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Shell运算符：Shell算数运算符、关系运算符、布尔运算符、字符串运算符、文件测试运算符"><span class="nav-number">6.</span> <span class="nav-text">Shell运算符：Shell算数运算符、关系运算符、布尔运算符、字符串运算符、文件测试运算符</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">
  
  &copy;  2017 - 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">MarsLeo Guo</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>


        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/blog/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.1"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.1"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.1"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

</body>
</html>
